package net.gazhi.delonix.weixin.mp.web;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

public class SignatureUtil {

	private static final char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static boolean checkSignature(HttpServletRequest request, String token) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		try {
			return checkSignature(signature, timestamp, nonce, token);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private static boolean checkSignature(String signature, String timestamp, String nonce, String token) throws NoSuchAlgorithmException, UnsupportedEncodingException {

		if (StringUtils.isEmpty(signature) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(nonce) || StringUtils.isEmpty(token)) {
			return false;
		}

		String[] strs = new String[] { timestamp, nonce, token };
		Arrays.sort(strs);
		String str = StringUtils.arrayToDelimitedString(strs, "");

		MessageDigest md = MessageDigest.getInstance("SHA-1");
		byte[] digest = md.digest(str.getBytes("UTF-8"));
		String tmpStr = byteToStr(digest);

		return tmpStr != null && tmpStr.equalsIgnoreCase(signature);
	}

	private static String byteToStr(byte[] byteArray) {
		int len = byteArray.length;
		StringBuilder strDigest = new StringBuilder(len * 2);
		for (byte aByteArray : byteArray) {
			strDigest.append(byteToHexStr(aByteArray));
		}
		return strDigest.toString();
	}

	private static String byteToHexStr(byte mByte) {
		char[] tempArr = new char[2];
		tempArr[0] = digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = digit[mByte & 0X0F];
		return new String(tempArr);
	}

}
